package com.github.cosycode.imgtool.rule;

import com.github.cosycode.common.ext.bean.DoubleBean;
import com.github.cosycode.common.lang.WrongBranchException;
import com.github.cosycode.imgtool.util.PathUtils;
import lombok.NonNull;
import org.apache.commons.lang3.Validate;

import java.io.File;
import java.util.function.UnaryOperator;

/**
 * <b>Description : </b>
 * <p>
 * <b>created in </b> 2022/8/7
 * </p>
 *
 * @author pengfchen
 * @since 1.0
 **/
public class MigrationPathConvert {

    public static final String MD_FILE_NAME_REG = "${mdFileName}";

    private PathUtils.PathType targetPathType;
    private String pathExpress;

    private UnaryOperator<String> nameRule;

    public MigrationPathConvert(PathUtils.PathType pathType, String pathExpress, UnaryOperator<String> nameRule) {
        this.targetPathType = pathType;
        this.pathExpress = pathExpress;
        this.nameRule = nameRule;
        check();
    }

    public boolean check() {
        if (PathUtils.PathType.ROOT_PATH.equals(targetPathType)) {
            PathUtils.PathType type = PathUtils.getPathType(pathExpress);
            Validate.isTrue(PathUtils.PathType.ROOT_PATH == type);
            Validate.isTrue(!pathExpress.contains(".."));
        } else if (PathUtils.PathType.ABSOLUTE_PATH.equals(targetPathType)) {
            PathUtils.PathType type = PathUtils.getPathType(pathExpress);
            Validate.isTrue(PathUtils.PathType.RELATION_PATH == type);
            Validate.isTrue(!pathExpress.contains(".."));
        } else {
            throw new WrongBranchException("not support");
        }
        return true;
    }


    /**
     * @param config  文件都说配置
     * @param txtFile 搜索的 markdown 文件
     * @param rst     img 链接检查结果
     * @return markdown 文件link 和 实际文件存放路径
     */
    public DoubleBean<String, String> computeTargetPath(CheckConfig config, File txtFile, FileExistCheckBRO rst) {
        String path = pathExpress;
        String name = txtFile.getName();
        // 1. 生成的路径必须为相对路径
        if (pathExpress.contains(MD_FILE_NAME_REG)) {
            path = pathExpress.replace(MD_FILE_NAME_REG, name);
        }
        @NonNull String imgTargetPath;
        @NonNull String imgLinkPrefix;
        switch (targetPathType) {
            case ROOT_PATH:
                // 此时 path: /..
                imgLinkPrefix = PathUtils.concatPathClips(path, nameRule.apply(name));
                imgTargetPath = PathUtils.concatPathClips(config.getRootPath(), imgLinkPrefix);
                break;
            case RELATION_PATH:
                // 此时 path: ./
                imgLinkPrefix = PathUtils.concatPathClips(path, nameRule.apply(name));
                imgTargetPath = PathUtils.concatPathClips(rst.getRealImgPath(), imgLinkPrefix);
                break;
            default:
                throw new WrongBranchException("not support");
        }
        return DoubleBean.of(imgLinkPrefix, imgTargetPath);
    }

}
